package org.netwia.networks;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.netwia.utils.ValidationUtils;

/**
 * This implementation of output listener pushes data to another output listener. 
 * 
 * @author radek.hecl
 *
 * @param <T> type of the network parameter
 */
public class ProxyOutputListener<T> implements OutputListener<T> {

    /**
     * Builder object.
     * 
     * @param <T> type of the network parameter
     */
    public static class Builder<T> {

        /**
         * Target output listener.
         */
        private OutputListener<T> target;

        /**
         * Sets target output listener.
         * 
         * @param target target output listener
         * @return this instance
         */
        public Builder<T> setTarget(OutputListener<T> target) {
            this.target = target;
            return this;
        }
        
        /**
         * Builds the result object.
         * 
         * @return created object
         */
        public ProxyOutputListener<T> build() {
            return new ProxyOutputListener<T>(this);
        }
    }

    /**
     * Target output listener.
     */
    private OutputListener<T> target;

    /**
     * Creates new instance.
     * 
     * @param builder builder object
     */
    public ProxyOutputListener(Builder<T> builder) {
        target = builder.target;
        guardInvariants();
    }

    /**
     * Guards this object to be consistent. Throws exception if this is not the case.
     */
    private void guardInvariants() {
        ValidationUtils.guardNotNull(target, "target cannot be null");
    }

    @Override
    public void outputProduced(T output) {
        target.outputProduced(output);
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

}
